#!/bin/bash

echo "========================================"
echo "启动 Nuxt3 前端 + Node.js 后端服务"
echo "========================================"
echo

# 检查Node.js是否安装
if ! command -v node &> /dev/null; then
    echo "错误: 未找到 Node.js，请先安装 Node.js"
    exit 1
fi

echo "Node.js 版本:"
node --version
echo

# 检查后端依赖
echo "检查后端依赖..."
cd backend
if [ ! -d "node_modules" ]; then
    echo "安装后端依赖..."
    npm install
    if [ $? -ne 0 ]; then
        echo "错误: 后端依赖安装失败"
        exit 1
    fi
fi
cd ..

# 检查前端依赖
echo "检查前端依赖..."
if [ ! -d "node_modules" ]; then
    echo "安装前端依赖..."
    npm install
    if [ $? -ne 0 ]; then
        echo "错误: 前端依赖安装失败"
        exit 1
    fi
fi

echo
echo "========================================"
echo "服务信息:"
echo "前端服务: http://localhost:3000"
echo "后端服务: http://localhost:3002"
echo "后端健康检查: http://localhost:3002/health"
echo "========================================"
echo

# 启动后端服务
echo "启动后端服务..."
cd backend
npm run dev &
BACKEND_PID=$!
cd ..

# 等待后端服务启动
echo "等待后端服务启动..."
sleep 3

# 启动前端服务
echo "启动前端服务..."
npm run dev &
FRONTEND_PID=$!

echo
echo "========================================"
echo "服务启动完成！"
echo
echo "前端服务: http://localhost:3000"
echo "后端服务: http://localhost:3002"
echo
echo "按 Ctrl+C 停止所有服务"
echo "========================================"

# 等待用户中断
trap 'echo "正在关闭所有服务..."; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo "服务已关闭"; exit 0' INT

# 等待进程结束
wait 